package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

/**
 * This class represents bank and allow you to add clients to the bank
 * 
 * @author Anton Kotov
 * 
 */
@SuppressWarnings("serial")
public class Bank implements Serializable {
    private Set<Client> clients = new HashSet<>();
    private List<ClientRegistrationListener> listeners = new ArrayList<>();

    public Bank(ClientRegistrationListener... listeners) {
	for (ClientRegistrationListener listener : listeners) {
	    if (listener == null) {
		throw new IllegalArgumentException();
	    }
	    this.listeners.add(listener);
	}
    }

    public Set<Client> getClients() {
	return Collections.unmodifiableSet(clients);
    }

    public Bank addClient(Client client) throws ClientExistsException {
	if (client == null) {
	    throw new IllegalArgumentException();
	}
	if (!clients.add(client)) {
	    throw new ClientExistsException(client.getName());
	}

	for (ClientRegistrationListener listener : listeners) {
	    listener.onClientAdded(client);
	}

	return this;
    }

    public Bank addClientRegistrationListener(
	    ClientRegistrationListener listener) {
	if (listener == null) {
	    throw new IllegalArgumentException();
	}
	listeners.add(listener);

	return this;
    }
}
